<?php
/**
 * Copyright (c) 2018. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/**
 * 支付中心API
 * Created by PhpStorm.
 * User: poptser
 * Email: poptser@foxmail.com
 * Date: 2016/8/16
 * Time: 14:05
 */

namespace SDXApi\Model;
use Com\Jdpay\JdpaySubmit;
use Com\Alipay\AlipaySubmit;
use SDXApi\Controller\BscController;
use SDXApi\Service\OrderDistributionTimeService;
use Think\Model;
use Think\Log;

class PaymentModel extends Model
{

    private function get_config($pay_id){
        //return $this->where(array("pay_id"=>$pay_id,"enabled"=>1))->getField("pay_config");
        $array = array(
            'seller_id' => C('ali_pay_parent'),//'2088811720960505',                                          //合作身份者ID
            'partner' => C('ali_pay_parent'),//'2088811720960505',                                            //合作身份者ID
            'key' => C('ali_pay_new_key'),//'cgfk1p3u0dngsghykks56rezaxqsbkpu',                                //KEY
            'transport' => 'http',
            'payment_type' => '1',
            'service' => 'alipay.wap.create.direct.pay.by.user',
            'sign_type' => strtoupper('MD5'),
            'input_charset' => strtolower('utf-8')
        );
        return $array;
    }
    
    private function get_app_config(){
    	$ROOT =  str_replace('\\','/',realpath(dirname(__FILE__).'/../../').'/');
    	//支付宝app支付2.0接口参数设置，留着备用
//     	$array = array(
//     			'app_id'=>'2016062801559463',
//     			'method'=>'alipay.trade.app.pay',
//     			'format'=>'JSON',
//     			'charset'=>strtolower('utf-8'),
//     			'sign_type' => strtoupper('RSA'),
//     			'version'=>'1.0',
//     			'seller_id'=>'2088811720960505',
//     			'product_code'=>'QUICK_MSECURITY_PAY',
//     			'private_key_path'=>$ROOT.'api/key/rsa_private_key.pem'

//     	);
    	$array = array(
            'seller_id' => C('ali_pay_account'),//'admin@shidexian.com',                                          //账号
            'partner' => C('ali_pay_parent'),//'2088811720960505',                                            //合作身份者ID
            'key' => C('ali_pay_new_key'),//'cgfk1p3u0dngsghykks56rezaxqsbkpu',                                //KEY
            'transport' => 'http',
            'payment_type' => '1',
            'service' => 'mobile.securitypay.pay',
            'sign_type' => strtoupper('RSA'),
            'input_charset' => strtolower('utf-8'),
            'private_key_path'=>$ROOT.'api/key_old/rsa_private_key.txt'
        );
        return $array;
    }

    private function get_scan_pay_config(){
        $ROOT =  str_replace('\\','/',realpath(dirname(__FILE__).'/../../').'/');

        $array = array (
            'alipay_public_key' => $ROOT . "api/scan_key/alipay_rsa_public_key.pem",
            'merchant_private_key' => $ROOT . "api/scan_key/rsa_private_key.pem",
            'merchant_public_key_file' => $ROOT . "api/scan_key/rsa_public_key.pem",
            'charset' => "utf-8",
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            'app_id' => C('ali_pay_appid'),//"2016051601404277",
            //最大查询重试次数
            'MaxQueryRetry' => "10",
            //查询间隔
            'QueryDuration' => "3",
            'sign_type'=>'RSA'
        );

        return $array;
    }


    /**
     * 支付宝支付
     * @param $out_trade_no
     * @param $subject_name
     * @param $total_fee
     * @param $show_url
     * @param $body
     * @param $notify_url
     * @param $return_url
     * @param int $order_type
     * @param bool $no_s 是否不拼接S  默认拼接
     * @return \Com\Alipay\提交表单HTML文本
     */
    public function alipay($out_trade_no, $subject_name, $total_fee, $show_url, $body,$notify_url,$return_url,$order_type=PAY_SURPLUS, $no_s=false){
        $alipay_config = $this->get_config();
        $parameter = array(
            "service"       => $alipay_config['service'],
            "partner"       => $alipay_config['partner'],
            "seller_id"  => $alipay_config['seller_id'],
            "payment_type"	=> $alipay_config['payment_type'],
            "notify_url"	=> $notify_url,
            "return_url"	=> $return_url,
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
            "out_trade_no"	=> $no_s ? $out_trade_no : $out_trade_no."s".$order_type,//1 会员预付款   0 会员支付订单
            "total_fee"	=> $total_fee,
            "show_url"	=> $show_url,
            "app_pay"	=> "Y",//启用此参数能唤起钱包APP支付宝
            "body"	=> $body,
            "subject"	=> $body.":".$total_fee
        );
        //return $parameter;
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        return $html_text;
        //dump($html_text);
        //echo $html_text;
    }

    /**
     * 支付宝app支付
     * @param $out_trade_no
     * @param $subject_name
     * @param $total_fee
     * @param $show_url
     * @param $body
     * @param $notify_url
     * @param $return_url
     * @param int $order_type
     * @param bool $no_s 是否不拼接S  默认拼接
     * @return \Com\Alipay\要请求的参数数组字符串
     */
    public function app_alipay($out_trade_no, $subject_name, $total_fee, $show_url, $body,$notify_url,$return_url,$order_type=PAY_SURPLUS, $no_s=false){
    	$alipay_config = $this->get_app_config();
    	$parameter = array(
    			"service"       => $alipay_config['service'],
    			"partner"       => $alipay_config['partner'],
    			"seller_id"  => $alipay_config['seller_id'],
    			"payment_type"	=> $alipay_config['payment_type'],
    			'sign_type' => $alipay_config['sign_type'],
    			"notify_url"	=> $notify_url,
    			"_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
    			"out_trade_no"	=> $no_s ? $out_trade_no : $out_trade_no."s".$order_type,//1 会员预付款   0 会员支付订单
    			"total_fee"	=> $total_fee,
    			"body"	=> $body,
    			"subject"	=> $body.":".$total_fee,
                "timeout_express"=>"30m"
    	);
    	 
    	$alipaySubmit = new AlipaySubmit($alipay_config);
    	$payinfo = $alipaySubmit->buildRequestParaToString($parameter);
    	
    	return $payinfo;
    	
    	//业务参数，支付宝app支付2.0接口参数设置，留着备用
//     	$order_info = array(
//     			"out_trade_no"	=> $out_trade_no."s".$order_type,//1 会员预付款   0 会员支付订单
//     			"subject"	=> $subject_name,
//     			"total_amount"	=> $total_fee,
//     			"body"	=> $body,
//     			"subject"	=> $body.":".$total_fee,
//     			'product_code'=>$alipay_config['product_code']
//     	);

    //公共参数，支付宝app支付2.0接口参数设置，留着备用
//     	$parameter = array(
//     			'app_id'=>$alipay_config['app_id'],
//     			'method'=>$alipay_config['method'],
//     			'format'=>$alipay_config['format'],
//     			'charset'=>$alipay_config['charset'],
//     			'sign_type'=>$alipay_config['sign_type'],
//     			'timestamp'=>date("Y-m-d H:i:s"),
//     			'version'=>$alipay_config['version'],
//     			'notify_url'=>$notify_url,
//     			'biz_content'=>json_encode($order_info)
//     	);
    //支付宝app支付2.0接口调用方法，留着备用
//     	$payinfo = $alipaySubmit->buildAppRequestParaToString($parameter);
//   		return $payinfo;
}

    /**
     * 支付宝二维码扫码支付
     * @param $out_trade_no
     * @param $subject_name
     * @param $total_fee
     * @param $show_url
     * @param $body
     * @param $notify_url
     * @param $return_url
     * @param int $order_type
     * @return \AlipayF2FPrecreateResult
     */
    public function scan_alipay($out_trade_no, $subject_name, $total_fee, $show_url, $body,$notify_url,$return_url,$order_type=PAY_SURPLUS){
        $alipay_config = $this->get_scan_pay_config();
        $parameter = array(
            "charset"	=> trim(strtolower($alipay_config['charset'])),
            "out_trade_no"	=> $out_trade_no."s".$order_type,//1 会员预付款   0 会员支付订单
            "total_fee"	=> $total_fee,
            "body"	=> $body,
            "subject"	=> $body.":".$total_fee
        );
        $alipay_config['notify_url'] = $notify_url;
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $payinfo = $alipaySubmit->buildQrcode($parameter);

        return $payinfo;
    }


    /**
     * 京东支付
     * @param $out_trade_no
     * @param $subject_name
     * @param $total_fee
     * @param $body
     * @param $notify_url
     * @param $return_url
     * @param int $order_type
     * @param string $uid
     * @param bool $no_s 是否不拼接S  默认拼接
     * @return mixed
     */
    public function jdpay($out_trade_no, $subject_name, $total_fee, $body,$notify_url,$return_url,$order_type=PAY_SURPLUS,$uid="", $no_s=false){
        $parameter = array(
            "version"   =>  C('JD_VERSION'),
            "merchant"  =>  C('JD_MERCHANT'),
            "tradeNum"  =>  $no_s ? $out_trade_no : $out_trade_no."s".$order_type,//1 会员预付款   0 会员支付订单
            "tradeName"	=>  $body,
            "tradeDesc" =>  $subject_name,
            "tradeTime" =>  date('YmdHis'),
            "amount"    =>  strval($total_fee*100),
            "currency"  =>  "CNY",
            "note"  =>  $subject_name,
            "callbackUrl"   =>  $return_url,
            "notifyUrl" =>  $notify_url,
            "userId"    =>  strval($uid),
            "orderType" =>  strval($order_type) //0为实物（订单支付），1为虚拟（充值）
        );

        $jdpaySubmit = new JdpaySubmit();
        $html_text = $jdpaySubmit->buildRequestForm($parameter,"post", "确认");
        return $html_text;
    }


    /**
 * 京东app支付
 * @param $out_trade_no
 * @param $subject_name
 * @param $total_fee
 * @param $body
 * @param $notify_url
 * @param $return_url
 * @param int $order_type
 * @param string $uid
 * @param bool $no_s 是否不拼接S  默认拼接
 * @return \Com\Jdpay\要请求的参数数组字符串
 */
    public function app_jdpay($out_trade_no, $subject_name, $total_fee, $body,$notify_url,$return_url,$order_type=PAY_SURPLUS,$uid="", $no_s=false){
        $parameter = array(
            "version"   =>  C('JD_VERSION'),
            "merchant"  =>  C('JD_MERCHANT'),
            "tradeNum"  =>  $no_s ? $out_trade_no : $out_trade_no."s".$order_type,//1 会员预付款   0 会员支付订单
            "tradeName"	=>  $body,
            "tradeDesc" =>  $subject_name,
            "tradeTime" =>  date('YmdHis'),
            "amount"    =>  strval($total_fee*100),
            "currency"  =>  "CNY",
            "note"  =>  $subject_name,
            "callbackUrl"   =>  $return_url,
            "notifyUrl" =>  $notify_url,
            "userId"    =>  strval($uid),
            "orderType" =>  strval($order_type) //0为实物（订单支付），1为虚拟（充值）
        );

        $jdpaySubmit = new JdpaySubmit();
        $payinfo = $jdpaySubmit->buildAppRequestParaToString($parameter);
        return $payinfo;
    }

    /**
     * 京东扫码支付
     * @param $out_trade_no
     * @param $subject_name
     * @param $total_fee
     * @param $body
     * @param $notify_url
     * @param $return_url
     * @param int $order_type
     * @param string $uid
     * @return \Com\Jdpay\要请求的参数数组字符串
     */
    public function scan_jdpay($out_trade_no, $subject_name, $total_fee, $body,$notify_url,$return_url,$order_type=PAY_SURPLUS,$uid=""){
        $parameter = array(
            "version"   =>  C('JD_VERSION'),
            "merchant"  =>  C('JD_MERCHANT'),
            "tradeNum"  =>  $out_trade_no."s".$order_type,//1 会员预付款   0 会员支付订单
            "tradeName"	=>  $body,
            "tradeDesc" =>  $subject_name,
            "tradeTime" =>  date('YmdHis'),
            "amount"    =>  strval($total_fee*100),
            "currency"  =>  "CNY",
            "note"  =>  $subject_name,
            "callbackUrl"   =>  $return_url,
            "notifyUrl" =>  $notify_url,
            "userId"    =>  strval($uid),
            "orderType" =>  strval($order_type), //0为实物（订单支付），1为虚拟（充值）
            "tradeType" =>  "QR"
        );

        $jdpaySubmit = new JdpaySubmit();
        $payinfo = $jdpaySubmit->buildAppRequestParaToString($parameter);
        return $payinfo;
    }




    /**
     * 插入支付记录
     * @param $surplus
     * @param $amount
     * @return int
     */
    public function add_recharge_log($surplus, $amount){
        //创建支付时调用
        $surplus['rec_id'] = $this->insert_user_account($surplus,$amount);
        $pay_log_id = $this->insert_pay_log($surplus['rec_id'], $amount, $type = PAY_SURPLUS, 0);
		//w_log("Application/Runtime/alipay","put pay id:".$pay_log_id);
        return $pay_log_id;
    }

    
    //检测充值金额是否可充
    function check_Recharge_amount($uid,$amount){
        $Recharge_amount=$this->Recharge_header();
        $user_rank = M("users")->where(array("user_id"=>$uid))->getField("user_rank");
        $user_is_upgrade_vip = M("users")->where(array("user_id"=>$uid))->getField("is_upgrade_vip");
        foreach($Recharge_amount as $item){
            if(floatval($item['charge'])==floatval($amount)){
                if(!in_array($user_rank,$item['rank']) && !(in_array(3,$item['rank']) && $user_is_upgrade_vip=='0')){
                    returnApiError('此充值无效，请选择其他充值！');
                }
                
                if($item['retrict']['limit']>0){
                    $where=array("is_pay"=>1,'admin_note'=>array('neq','混合支付'),"user_id"=>$uid,"amount"=>array("in",$item['retrict']['amount']));
                    if($item['expire_time']['start']>0 and $item['expire_time']['end']>0){
                        $where['paid_time']=array('between',$item['expire_time']['start'].",".$item['expire_time']['end']);
                    }
                    $recharge_num = M("user_account")->field("user_id")->where($where)->count();
                    if($recharge_num>=$item['retrict']['limit']){
                        returnApiError('抱歉，此活动充值只能充值'.$item['retrict']['limit'].'次！');
                    }
                }
                
                break;
            }
        }
        
    }
    
    //活动充值金额定义
    public function Recharge_header(){
        
        $re_list=M("recharge_setting")->order("recharge_type desc,recharge_amount desc")->select();
        foreach($re_list as $item){
            $content=array();
            $recharge_ext=unserialize($item['recharge_ext']);
            if(!empty($recharge_ext)){
                $i=0;
                $font_size_a='18';
                if(count($recharge_ext)>1){
                    $font_size_a='15';
                }
                $is_block='0';
                foreach($recharge_ext as $item3){
                    if($i>0){
                        $is_block='1';
                    }
                    $content[]=array(
                                    'text'=>$item3,
                                    'font_size_a'=>$font_size_a,
                                    'font_size_i'=>'12',
                                    'font_size_h5'=>'1',
                                    'is_block'=>$is_block
                                );
                    $i++;
                }
            }

            $recharge_ext2=unserialize($item['recharge_ext2']);
            $recharge_ext2_list=array();
            if(!empty($recharge_ext2)){
                foreach($recharge_ext2 as $item3){
                    if($item3['goods_num']>0 && gmstr2time($item3['goods_start'])<=gmtime() && (gmstr2time($item3['goods_end'])+86400)>gmtime()){
                        $recharge_ext2_list[]=$item3;
                    }
                }
            }

            $allow_rank=array();
            foreach(unserialize($item['allow_rank']) as $item2){
                if($item2=='1'){
                    $allow_rank[]='0';
                }
                $allow_rank[]=$item2;
            }
            
            $Recharge_amount[]=array('charge'=>$item['recharge_amount'],'gift'=>$item['gift_recharge_amount'],'rank'=>$allow_rank,'retrict'=>array('limit'=>$item['user_limit'],'amount'=>$item['recharge_amount']),'expire_time'=>array('start'=>$item['start_time'],'end'=>$item['end_time']),'is_activity'=>$item['recharge_type'],'content'=>$content,'is_send_msg'=>$item['is_send_msg'],'send_msg_op'=>$item['send_msg_op'],'send_msg_text'=>$item['send_msg_text'],'bonus_ext'=>unserialize($item['bonus_ext']),'is_limit'=>$item['is_limit'],'recharge_limit_count'=>$item['recharge_limit_count'],'is_become_vip'=>$item['is_become_vip'],'recharge_ext2'=>$recharge_ext2_list);
        }
        
        
        
        $Recharge_amount_list=array();
        foreach($Recharge_amount as $list){
            if($list['is_limit']=='1' && $list['recharge_limit_count']>0){
                $where=array("is_paid"=>1,"process_type"=>'0','admin_note'=>array('neq','混合支付'),"amount"=>array("in",$list['charge']));
                if($list['expire_time']['start']>0 and $list['expire_time']['end']>0){
                    $where['paid_time']=array('between',$list['expire_time']['start'].",".$list['expire_time']['end']);
                }
                $recharge_num = M("user_account")->field("user_id")->where($where)->count();
                
                if($recharge_num>=$list['recharge_limit_count']){
                    continue;
                }
            }
            
            if($list['expire_time']['start']<gmtime() && $list['expire_time']['end']>gmtime() || $list['expire_time']['start']==0 && $list['expire_time']['end']==0){
                $start=local_date("m月d日 H:i",$list['expire_time']['start']).'-'.local_date("m月d日 H:i",gmtime());
                $end=local_date("m月d日 H:i",$list['expire_time']['end']).'-'.local_date("m月d日 H:i",gmtime());
                if($list['expire_time']['start']>0 && $list['expire_time']['end']>0){
                    $list['expire']='活动时间：'.local_date("m月d日",$list['expire_time']['start']).' - '.local_date("m月d日",$list['expire_time']['end']);
                }
                
                $Recharge_amount_list[]=$list;
            }
        }
        
       
        return $Recharge_amount_list;
    }
    
    //活动充值处理
    public function add_Recharge($data){
        
        if($data['admin_note']!='混合支付'){
            $Recharge_amount=$this->Recharge_header();
            $user_rank = M("users")->where(array("user_id"=>$data['user_id']))->getField("user_rank");
            $user_is_upgrade_vip = M("users")->where(array("user_id"=>$data['user_id']))->getField("is_upgrade_vip");
            
            
            foreach($Recharge_amount as $item){
                if(floatval($item['charge'])==floatval($data['amount'])){
                    if(!in_array($user_rank,$item['rank']) && !(in_array(3,$item['rank']) && $user_is_upgrade_vip=='0')){
                        return false;
                    }
                    
                    if($item['retrict']['limit']>0){
                        $where=array("is_pay"=>1,'admin_note'=>array('neq','混合支付'),"user_id"=>$data['user_id'],"amount"=>array("in",$item['retrict']['amount']));
                        if($item['expire_time']['start']>0 and $item['expire_time']['end']>0){
                            $where['paid_time']=array('between',$item['expire_time']['start'].",".$item['expire_time']['end']);
                        }
                        $recharge_num = M("user_account")->field("user_id")->where($where)->count();
                        if($recharge_num>=$item['retrict']['limit']){
                            return false;
                        }
                    }
                    
                    
                    $users = M("users")->field("user_money,mobile_phone,user_id,user_name")->where(array("user_id"=>$data['user_id']))->find();
                    
                    $log_id=$this->insert_account_log($data['user_id'],$data['amount'],0,0,0,"充".$data['amount']."送".$item['gift']."活动充值金额");
                    //赠送金额
                    if(floatval($item['gift'])>0){
                            $this->insert_account_log($data['user_id'],$item['gift'],0,0,0,"充".$data['amount']."送".$item['gift']."活动赠送金额",7,$log_id);
                        
                        $surplus['user_id'] = $data['user_id'];
                        $surplus['amount'] = $item['gift'];
                        $surplus['admin_note'] = "充".floatval($data['amount'])."送".($item['gift'])."活动赠送金额";
                        $surplus['user_note'] = 0;
                        $surplus['payment'] = '赠送';
                        $surplus['process_type'] = 7;
                        $surplus['change_type'] = 7;
                        $surplus['is_paid'] = 1;
                        $this->add_recharge_log($surplus,$surplus['amount']);
                        $this->updata_users_money($data['user_id'],$item['gift']);
                        //赠送日志
                        D('Users')->write_user_action("buyer",$data ['user_id'],"赠送",$users['user_money'],$users['user_money']+$item['gift']);	//写日志
                        
                        
                        
                    
                    }
                    
                    //赠送红包
                    if(count($item['bonus_ext'])>0){
                        foreach($item['bonus_ext'] as $item2){
                            if(!empty($item2)){
                                for($i=0;$i<$item2['bonus_num'];$i++){
                                    $this->recharge_bonus($data['user_id'],$item2['bonus_id']);
                                }
                                
                            }
                        }   
                    }

                    //赠送商品
                    if(count($item['recharge_ext2'])>0){
                        foreach($item['recharge_ext2'] as $item2){

                                $goods_info=M("goods")->where(array('goods_id'=>$item2['goods_id']))->find();
                                $cartdata=array();
                                $cartdata['user_id']=$data['user_id'];
                                $cartdata['goods_id']=$goods_info['goods_id'];
                                $cartdata['goods_sn']=$goods_info['goods_sn'];
                                $cartdata['goods_name']=$goods_info['goods_name'];
                                $cartdata['market_price']=$goods_info['market_price'];
                                $cartdata['goods_price']=0;
                                $cartdata['goods_number']=$item2['goods_num'];
                                $cartdata['expiration_date']=gmstr2time($item2['goods_end']);
                                $cartdata['is_real']=1;
                                $cartdata['giving']=6;
                                $cartdata['is_check']=1;
                                $cartdata['act_id']=0;
                                M("cart")->add($cartdata);

                        }
                    }
                    
                    //如果满足充值要求，成为会员
                    if($item['is_become_vip']=='1'){
                        M('users')->where(array('user_id'=>$data['user_id']))->setField('user_rank',2);
                    
                        //写入会员变更为注册用户记录
                        $action_time_rui = M('user_action')->where(array("user_id"=>$data ['user_id'],"action_type"=>"降至注册用户"))->order("action_time desc")->getField("action_time");
                        if(empty($action_time_rui)){
                            $action_time_rui = local_date('Y-m-d H:i:s',$users['reg_time']);
                        }else{
                            local_date('Y-m-d H:i:s',$action_time_rui);
                        }
                        D('Users')->write_user_action("buyer",$data ['user_id'],"升至VIP",$action_time_rui,date('Y-m-d H:i:s',time()));	//写日志
                        if($user_is_upgrade_vip=='0'){
                            M('users')->where(array('user_id'=>$data['user_id']))->setField('is_upgrade_vip',1);
                        }
                    
                    }
                    
                    
                    if($item['is_send_msg']=='1'){
                        $user_name='食得鲜会员';
                        $get_consignee=M("order_info")->where(array('user_id'=>$data['user_id']))->getField("consignee");
                        if(!empty($get_consignee)){
                            $user_name=$get_consignee;
                        }
                        $chat_param=array();
                        switch($_SERVER['SERVER_NAME']){
                            case 'api.xian3.com':
                                $thisurl='xian3.com';
                                break;
                            case 'api.test.shidexian.com':
                                $thisurl='test.shidexian.com';
                                break;
                            case 'api.shidexian.com':
                                $thisurl='w.shidexian.com';
                                break;
                            default:
                                $thisurl='w.shidexian.com';
                                break;
                        }
                        $oid=$users['user_id'];
                        $Code=md5($users['user_id'].'sdx@9999');
                         
                        
                        
                        $chat_param['accountType']='用户名';
                        $chat_param['account']=$users['mobile_phone'];
                        $chat_param['amount']=sprintf("%.2f",$data['amount']+$item['gift']);
                        $chat_param['result']='成功';
                        
                        if($item['send_msg_op']=='1' && !empty($item['send_msg_text'])){
                            $chat_param['url']="https://".$thisurl."/?index=/money"."&utm_source=GZHRecharge_gift";
                            A("Smsapi")->send_message_api("Recharge_gift",$users['mobile_phone'],'食得鲜用户',0,0,0,$users['user_id'],array("amount"=>($data['amount']),"gift"=>$item['send_msg_text']),'',$chat_param);
                        }else{
                            $chat_param['url']="https://".$thisurl."/?index=/money"."&utm_source=GZHactivity_60_100_arrived";
                            A("Smsapi")->send_message_api("activity_60_100_arrived",$users['mobile_phone'],'食得鲜用户',0,0,0,$users['user_id'],array("amount"=>($data['amount']+$item['gift'])),'',$chat_param);
                        }
                    }
                    
                    
                    return true;
                    
                    break;
                    
                }
            }
        }
        

        
        
        return false;
    }
    
    //活动充值时间
    public function check_Recharge_time($uid){
       $type_list=array();
       $Recharge_amount=$this->Recharge_header();
       $user_is_upgrade_vip = M("users")->where(array("user_id"=>$uid))->getField("is_upgrade_vip");
       $user_rank = M("users")->where(array("user_id"=>$uid))->getField("user_rank");
       if($user_rank!='2'){
           $user_rank='1';
       }
       
       $type=1;
       foreach($Recharge_amount as $item){
          if(!in_array($user_rank,$item['rank']) && !(in_array(3,$item['rank']) && $user_is_upgrade_vip=='0')){
              continue;
          }
          
          if($item['retrict']['limit']>0){
              $where=array("is_paid"=>1,'admin_note'=>array('neq','混合支付'),"user_id"=>$uid,"amount"=>array("in",$item['retrict']['amount']));
              if($item['expire_time']['start']>0 and $item['expire_time']['end']>0){
                  $where['paid_time']=array('between',$item['expire_time']['start'].",".$item['expire_time']['end']);
              }
              $recharge_num = M("user_account")->field("user_id")->where($where)->count();
              if($recharge_num>=$item['retrict']['limit']){
                  continue;
              }
          }
          
          $is_expiring=0;
          $expiration_notice='';
          if($item['expire_time']['end']>0 && ($item['expire_time']['end']-gmtime())<=(3*24*60*60)){
              $is_expiring=1;
              $expiration_notice=$item['expire_time']['end']-gmtime();
          }
          
          $type_list[] = array (
              'type' => $type,
              'price' => floatval($item['charge']),
              'give_type' => '1',
              'descrition' => $item['content'],
              'give_price' => 0,
              'expire' => $item['expire'],
              'expire_time'=>'',
              'is_expiring'=>$is_expiring,
              'activity_limit_notice_time'=>'',
              'expiration_notice'=>$expiration_notice,
              'pic' => '' ,
              'is_activity' => $item['is_activity'],
              'is_become_vip' => $item['is_become_vip']
          );
          
          $type++;
          
       }
       
      
        
        return $type_list;
    }

    /**
     * todo 更新支付记录
     * @param $rec_id
     * @param $type
     */
    public function updata_recharg_log($pay_log_id){
        
        //支付成功时调用 157
		$order_id = $this->update_pay_log($pay_log_id,1,$order_type=PAY_SURPLUS);	//修改支付记录为已支付，并返回订单号

		if($order_id){
		    //判断是否符合充60送100元活动
		    $data = M("user_account")->where(array("id"=>$order_id))->find();
		    
		    $delay_time=$this->add_Recharge($data);
			//根据订单号 更新用户user_account 表
			$re = $this->update_user_account($order_id);
			if($re){
				//插入用户账户记录表
				$data = M("user_account")->where(array("id"=>$order_id))->find();
				$users = M("users")->field("user_money")->where(array("user_id"=>$data['user_id']))->find();
				//充值日志
				D('Users')->write_user_action("buyer",$data ['user_id'],$data['payment'],$users['user_money'],$users['user_money']+$data['amount']);	//写日志
				
				if(!$delay_time){
				    
				    $this->insert_account_log($data['user_id'],$data['amount']);
				}
				
				
				
				
				return $this->updata_users_money($data['user_id'],$data['amount']);
				
				
				
			}else{
				//w_log("Application/Runtime/alipay","update_user_account:fail");
			}
		}else{
			//w_log("Application/Runtime/alipay","change_pay_type:fail");
		}
	}
	
	
	/**
	 * 更新充60送100元 2016-11-16。金额到帐处理
	 */
	public function updata_60_100_user_account(){
	    
	    if(gmtime()>strtotime("2016-11-16")){
	        $Model=new Model(); 
	        $sql = "SELECT * from sdx_user_account where delay_time='".strtotime("2016-11-16")."' and is_paid='1' and is_into_amount=0";
	        $list_user_account = $Model->query($sql);
	        
	        foreach($list_user_account as $item){
	            $state=$this->updata_users_money($item['user_id'],$item['amount']);
	            if($state){
	                M("user_account")->where(array("id"=>$item['id']))->setField(array('is_into_amount'=>'1',"deposit_time"=>gmtime()));
	                $users = M("users")->field("password,paypwd",true)->where(array("user_id"=>$item['user_id']))->find();
	                A("Smsapi")->send_message_api("activity_60_100_arrived",$users['mobile_phone'],$users['mobile_phone'],0,0,0,$users['user_id'],array("amount"=>$item['amount']));
	                
	                
	            }
	            
	        }
	    }
	    return true;
	    
	}
	
	/**
     * 充值满条件发放红包
     */
	public function recharge_bonus($uid, $type_id) {
		$curtime = gmtime ();
		$where = array ();
		$where ['send_start_date'] = array('ELT',$curtime);
		$where ['send_end_date'] = array('EGT',$curtime);
		$where ['type_id'] = $type_id;
		
		$recharge_bonus_list = M ( 'bonus_type' )->where ( $where )->select ();
        $record_sn_res=array();
		if(!empty($recharge_bonus_list)){
			foreach ( $recharge_bonus_list as $key_bonus => $bonus ) {
				//统计红包发放记录
				$map = array('bonus_type_id'=>$bonus['type_id'],'send_type'=>4);
				$rec_count = M('bonus_send_record')->where($map)->count();
				//如果超出发放名额数量，则不发放
				if($rec_count>=$bonus['limit_send_num'] && $bonus['limit_send_num']!=0){
					continue;
				}

                $deadline=$bonus['use_end_date'];
                if($bonus['has_effective_days']==1){
                    $deadline=$curtime+($bonus['effective_days']*24*60*60);
                    if($deadline>$bonus['use_end_date']){
                        $deadline=$bonus['use_end_date'];
                    }
                }
                
                

				/* 生成红包序列号 */
				$num = M ( 'user_bonus' )->max ( 'bonus_sn' );
				$num = $num ? floor ( $num / 10000 ) : 100000;
				for($i = 0, $j = 0; $i < $bonus ['send_num']; $i ++) {
					$bonus_sn = ($num + $i) . str_pad ( mt_rand ( 0, 9999 ), 4, '0', STR_PAD_LEFT );
					$bonus_data = array ();
					$bonus_data ['bonus_type_id'] = $bonus ['type_id'];
					$bonus_data ['bonus_sn'] = $bonus_sn;
					$bonus_data ['user_id'] = $uid;
                    $bonus_data ['get_time'] = $curtime;
                    $bonus_data ['deadline'] = $deadline;
					M ( 'user_bonus' )->add ( $bonus_data );
                    $record_sn_res[]=$bonus_sn;
					$j ++;
				}
				
				//记录红包发送记录
				$recorde = array();
				$recorde['bonus_type_id'] = $bonus ['type_id'];
				$recorde['user_id'] = $uid;
				$recorde['send_num'] = $bonus ['send_num'];
				$recorde['bonus_money'] = $bonus ['type_money'];
				$recorde['send_type'] = $bonus ['send_type'];
				$recorde['create_time'] = $curtime;
				
				M('bonus_send_record')->add($recorde);
			}
		}

        return $record_sn_res;
    }
    /**
     * 插入会员账目明细
     * @access  public
     * @param   array     $surplus  会员余额信息
     * @param   string    $amount   余额
     * @return  int
     */
    public function insert_user_account($surplus, $amount) { 
        if(isset($surplus['id'])){
            $data['id'] = $surplus['id'];
        }
        if(isset($surplus['delay_time'])){
            $data['delay_time'] = $surplus['delay_time'];
        }
        $data['user_id'] = $surplus['user_id'];
        $data['admin_user'] = '买家';
        $data['amount'] = $amount;
        $data['add_time'] = gmtime();
        $data['paid_time'] = 0;
        $data['admin_note'] =  $surplus['admin_note'];
        $data['user_note'] = $surplus['user_note'];
        $data['process_type'] = $surplus['process_type'];
        $data['payment'] = $surplus['payment'];
        if(isset($surplus['is_paid'])){
            $data['is_paid'] = $surplus['is_paid'];
        }else{
            $data['is_paid'] = 0;
        }
        $data['delay_time'] = isset($surplus['delay_time'])?$surplus['delay_time']:0;
        return M('user_account')->add($data);
    }

    /**
     * 更新会员账目明细
     * @access  public
     * @param   array     $surplus  会员余额信息
     * @return  int
     */
    public function update_user_account($order_id,$delay_time='') {
        $data['is_paid'] = 1;
		$data['paid_time'] = gmtime();
		if(!empty($delay_time)){
		    $data['delay_time'] = $delay_time;
		    $data['admin_note'] = "充60得100活动充值金额11.16号到账";
		}
        return M("user_account")->where(array("id"=>$order_id))->save($data);
    }

    /**
     * 将支付LOG插入数据表
     * @access  public
     * @param   integer     $id         订单编号
     * @param   float       $amount     订单金额
     * @param   integer     $type       支付类型
     * @param   integer     $is_paid    是否已支付
     * @return  int
     */
    public function insert_pay_log($id, $amount, $type = PAY_SURPLUS, $is_paid = 0) {
        $data['order_id'] = $id;
        $data['order_amount'] = $amount;
        $data['order_type'] = $type;
        $data['is_paid'] = $is_paid;
		return M('pay_log')->add($data);
    }

    /**
     * 支付记录标记为成功
     * @param $order_id
     */
	/**
	 * 支付记录标记为成功
	 * @param $order_id
	 */
	public function update_pay_log($log_id,$is_paid){
		$update = M("pay_log")->where(array("log_id"=>$log_id))->setField('is_paid',$is_paid);
		if($update){
			$order_id = M("pay_log")->where(array("log_id"=>$log_id,'is_paid'=>$is_paid))->getField('order_id');
			return $order_id;
		}
	}

    /**
     * 支付记录标记为成功
     * @param $log_id
     * @param $is_paid
     * @param int $order_type
     * @param array $trade_data
     * @return mixed
     */
    public function change_pay_type($log_id,$is_paid,$order_type=PAY_SURPLUS,$trade_data=array()){
        $save_data = array();
        $save_data['is_paid'] = $is_paid;
        if(!empty($trade_data) && !empty($trade_data['trade_no'])){
            $save_data['transid'] = $trade_data['trade_no'];
        }
    	$update = M("pay_log")->where(array("log_id"=>$log_id,'order_type'=>$order_type))->save($save_data);
		if($update){
			return M("pay_log")->where(array("log_id"=>$log_id,'is_paid'=>$is_paid))->getField('order_id');
		}

    }

    /**
     * 用户帐号情况记录表
     * @param $uid              users表中的user_id对应
     * @param $user_money       用户该笔记录的余额
     * @param $frozen_money     被冻结的资金
     * @param $rank_points      等级积分
     * @param $pay_points       消费积分
     * @param $change_desc      该笔操作的备注
     * @param int $change_type  操作类型，0为充值，1为提现，2为管理员调节，99为其他类型
     */
    public function insert_account_log($uid, $user_money, $frozen_money=0, $rank_points=0, $pay_points=0, $change_desc="充值", $change_type=0,$p_log_id=0){
        if(empty($uid)||empty($user_money)){
            return false;
        }else{
            $data['user_id'] =  $uid;
            $data['user_money'] =   $user_money;
            $data['frozen_money'] = $frozen_money;
            $data['rank_points'] =  $rank_points;
            $data['pay_points'] =   $pay_points;
            $data['change_time'] =  gmtime();
            $data['change_desc'] =  $change_desc;
            $data['change_type'] =  $change_type;
            $data['p_log_id'] =  $p_log_id;
            $re = M("account_log")->add($data);
            if($re){
                return $re;
            }else{
                return false;
            }
        }
    }

    /**
     * 更新用户金额
     * @param $uid
     * @param $user_money
     */
    public function updata_users_money($uid, $user_money){
        if($user_money>0){
            return M("users")->where('user_id='.$uid)->setInc('user_money',$user_money); // 用户的金额
        }else{

			return M("users")->where('user_id='.$uid)->setDec('user_money',$user_money); // 用户的
        }
    }
    
    public function get_paymeng_list(){
    	$map = array ();
    	$map['enabled'] = 1;
    	$res = $this->field ( 'pay_id,pay_code,pay_name,pay_desc' )->where ( $map )->order('pay_order')->select ();
    	$data = array ();
    	if ($res) {
    		$data ['list'] = $res;
    	}
    	return $data;
    }
    
    /**
     * 记录帐户变动
     * @param   int     $user_id        用户id
     * @param   float   $user_money     可用余额变动
     * @param   float   $frozen_money   冻结余额变动
     * @param   int     $rank_points    等级积分变动
     * @param   int     $pay_points     消费积分变动
     * @param   string  $change_desc    变动说明
     * @param   int     $change_type    变动类型：参见常量文件
     * @return  void
     */
    public function log_account_change($user_id, $user_money = 0, $frozen_money = 0, $rank_points = 0, $pay_points = 0, $change_desc = '', $change_type = ACT_OTHER)
    {
        /* 更新用户信息 */
        $sql = "UPDATE " . C('DB_PREFIX')."users
              SET user_money = user_money + ('$user_money')," .
            " frozen_money = frozen_money + ('$frozen_money')," .
            " rank_points = rank_points + ('$rank_points')," .
            " pay_points = pay_points + ('$pay_points')" .
            " WHERE user_id = '$user_id'";
        $model = new Model();
        $res = $model->execute($sql);

        if($res !== false){
            /* 插入帐户变动记录 */
            $account_log = array(
                'user_id'       => $user_id,
                'user_money'    => $user_money,
                'frozen_money'  => $frozen_money,
                'rank_points'   => $rank_points,
                'pay_points'    => $pay_points,
                'change_time'   => gmtime(),
                'change_desc'   => $change_desc,
                'change_type'   => $change_type
            );
            M('account_log')->add($account_log);
        }

        return $res;
    }
    
    
    
    
    /**
     * 设置红包为已使用
     * @param   int     $bonus_id   红包id
     * @param   int     $order_id   订单id
     * @return  bool
     */
    public function use_bonus($bonus_id, $order_id) {
    	$res = D('user_bonus')->where(array('bonus_id'=>$bonus_id))->save(array('order_id'=>$order_id,'used_time'=>gmtime()));
    	return $res;
    }
    
    /**
     * 处理订单支付成功后，保存订单信息以及相关业务处理
     * @param array $order 处理后的订单信息
     * @return array $order 返回最新的订单信息
     */
    public function payreturn($order,$order_type=PAY_ORDER){
    	$res = $this->saveorder($order);
    	if($res!==false){
//     		/* 处理余额、积分、红包 */
//     		if ($order ['user_id'] > 0 && $order ['surplus'] > 0) {
//     			$this->log_account_change($order ['user_id'], $order ['surplus'] * (- 1), 0, 0, 0, sprintf("支付订单 %s", $order ['order_sn']));
//     		}
//     		if ($order ['user_id'] > 0 && $order ['integral'] > 0) {
//     			$this->log_account_change($order ['user_id'], 0, 0, 0, $order ['integral'] * (- 1), sprintf("支付订单 %s", $order ['order_sn']));
//     		}
//     		if ($order ['bonus_id'] > 0) {
//     			$this->use_bonus($order ['bonus_id'], $order['order_id']);
//     		}
    		$order['log_id'] = $this->update_pay_log($order['order_id'],$order_type);
    		return $order;
    	}else{
    		return null;
    	}
    }
    
    /**
     * 修改订单内容
     * @param array $order 处理后的订单信息
     */
    public function saveorder($order){
    	$res = M('order_info')->where(array('order_id'=>$order['order_id']))->save($order);
    	return $res;
    }
    
    public function get_paylog_id($order_id,$order_type=PAY_ORDER){
    	return  M('pay_log')->where(array('order_id'=>$order_id,'order_type'=>$order_type))->getField('log_id');
    }
    
    /**
     * 修改订单的支付状态
     *
     * @access  public
     * @param   string  $log_id     支付编号
     * @param   integer $pay_status 状态
     * @param   string  $note       备注
     * @param   array   $order_type 订单类型
     * @param   array   $trade_data 支付回调数据
     * @return  void
     */
    public function order_paid($out_trade_no, $pay_status = PS_PAYED,$note = '', $order_type=PAY_ORDER,$trade_data = array()) {
    	$result = array();

    	/* 取得支付订单信息 */
    	$pay_order = $this->get_pay_log($out_trade_no,$order_type);
    	if(!empty($pay_order) && $pay_order['is_paid'] == 0){
    		$pay_log = D('pay_log');
    		$order_info = D('Orderinfo');
    		/* 修改此次支付操作的状态为已付款 */
    		$this->change_pay_type($pay_order['log_id'],1,$order_type,$trade_data);
    		/* 根据记录类型做相应处理 */
    		if ($pay_order['order_type'] == PAY_ORDER) {
    			if($pay_order['pay_status'] == PS_PAYED){
    				$msg = '详情请到用户中心订单详情查看。';
    				$pay_success = "订单已付款！" . $msg;
    				$result['pay_success'] = $pay_success;
    				return $result;
    			}
    			if($pay_order['pay_status'] == PS_UNPAYED){
    				//获取订单的支付方式
    				$pay_code = $this->get_pay_code($pay_order['pay_id']);
    				
    				/* 修改订单状态为已付款 */
    				$order ['order_status'] = OS_CONFIRMED;
    				$order ['confirm_time'] = gmtime();
    				$order ['pay_status'] = $pay_status;
    				$order ['pay_time'] = gmtime();

//     				returnApiError($pay_code);
    				//如果使用余额支付
    				if($pay_code=='balance'){
    					// 余额支付里如果输入了一个金额
    					if ($order ['surplus'] > 0) {
    						$order ['order_amount'] = $pay_order ['order_amount'] + $pay_order ['surplus'];
    					}else{
    						$order ['order_amount'] = $pay_order ['order_amount'];
    					}
    					$order ['surplus'] = $order ['order_amount'];
                        $res = $this->log_account_change($pay_order ['user_id'], $order ['surplus'] * (- 1), 0, 0, 0, sprintf("支付订单 %s", $pay_order ['order_sn']));
                        if($res===false){
                            returnApiError('支付失败，请重试');
                        }

                        //用户余额为0，会员等级降为普通会员
                        $user_money=D("Users")->get_user_money($pay_order ['user_id']);
                        if($user_money == 0){
                            $user_rank_rui = M('users')->where(array("user_id"=>$pay_order ['user_id']))->getField("user_rank");
                            if($user_rank_rui !=1){
                                M('users')->where(array("user_id"=>$pay_order ['user_id']))->save(array("user_rank"=>1));

                                //写入会员变更为注册用户记录
                                $action_time_rui = M('user_action')->where(array("user_id"=>$pay_order ['user_id'],"action_type"=>"升至VIP"))->order("action_time desc")->getField("action_time");
                                if(empty($action_time_rui)){
                                    $action_time_rui = "-";
                                }else{
                                    local_date('Y-m-d H:i:s',$action_time_rui);
                                }
                                D('Users')->write_user_action("buyer",$pay_order ['user_id'],"降至注册用户",$action_time_rui,date('Y-m-d H:i:s',time()));	//写日志
                            }

                        }

//     					returnApiError($order ['surplus']);
    				}else{
    					$order ['money_paid'] = $pay_order ['order_amount'];
    				}
    				$order ['order_amount'] = 0;

    				$map = array('order_id'=>$pay_order['order_id']);
    				$order_info->where($map)->save($order);

                    /* 是否开发票 */
                    $invoice = M('order_invoice')->field('invoice_id,invoice_title_type,invoice_title_content,invoice_remark,invoice_title_type')->where(array('order_id'=>$pay_order['order_id']))->find();
                    if($invoice){
                        $note = "申请开发票【id {$invoice['invoice_id']}】".($invoice['invoice_title_type']==1?'个人':'单位')."：{$invoice['invoice_title_content']} 备注：{$invoice['invoice_remark']} ".$note;
                    }
    				
    				/* 记录订单操作记录 */
    				$order_action = D ( 'order_action' );
    				$action_data = array ();
    				$action_data ['order_id'] = $pay_order ['order_id'];
    				$action_data ['action_user'] = "buyer";
    				$action_data ['order_status'] = OS_CONFIRMED;
    				$action_data ['shipping_status'] = $pay_order['shipping_status'];
    				$action_data ['pay_status'] = $pay_status;
    				$action_data ['action_place'] = 0;
    				$action_data ['action_note'] = $note;
    				$action_data ['log_time'] = gmtime ();
    				//收货地址坐标
    				$address = $order_info->get_address_gps($pay_order['country'], $pay_order['province'], $pay_order['city'], $pay_order['district'],$pay_order['address']);
    				$action_data ['longitude'] = $address['longitude'];
    				$action_data ['latitude'] = $address['latitude'];
    				$order_action->add ( $action_data );


    				
    				//使用余额支付，处理账户余额明细
//    				if($pay_code=='balance'){
//    					$this->log_account_change($pay_order ['user_id'], $order ['surplus'] * (- 1), 0, 0, 0, sprintf("支付订单 %s", $pay_order ['order_sn']));
//    				}
    				//$this->log_account_change($pay_order ['user_id'], $order ['surplus'] * (- 1), 0, 0, 0, sprintf("支付订单 %s", $pay_order ['order_sn']));
    				

    				//双12活动送红包 add by yangzhic start
                    D('Userbonus')->send_bonus_for_d12($pay_order['user_id'],$pay_order['order_id']);
                    //双12活动送红包 add by yangzhic end

    				/* 对虚拟商品的支持 */
    				$virtual_goods = $order_info->get_virtual_goods($pay_order['order_id']);
    				if (!empty($virtual_goods)) {
    					$msg = '';
    					$res = $order_info->virtual_goods_ship($virtual_goods, $msg, $pay_order['order_sn'], true);
    					$flag = $res['status'];
    					unset($res['status']);
    					$result = array_merge($res,$result);
    					if(!$flag){
    						$result['pay_success'] = '您此次的支付操作已成功！。<div style="color:red;">'.$msg.'</div>自动发货失败，请尽快联系商家重新发货！';
    					}
    					
    					/* 如果订单没有配送方式，自动完成发货操作 */
    					if ($order['shipping_id'] == -1) {
    						/* 将订单标识为已发货状态，并记录发货记录 */
    						$udata = array('shipping_status'=>SS_SHIPPED,'shipping_time'=>gmtime());
    						$order_info->where(array('order_id'=>$pay_order['order_id']))->setField($udata);
    						
    						/* 记录订单操作记录 */
    						$action_data['shipping_status'] = SS_SHIPPED;
    						$action_data['log_time'] = gmtime();
    						$order_action->add ( $action_data );
    						/* 计算并发放积分 */
    						$integral = $order_info->integral_to_give($pay_order);
    						$this->log_account_change($pay_order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf(L('order_gift_integral'), $pay_order['order_sn']));
    					}
    				}
//                    dump("dde");
//                    exit();
                    if($pay_order['order_id']>0){
                        $res=M('order_info')->where(array('order_id'=>$pay_order['order_id']))->find();

                        if($res){
                            //$order_list = $order_info->split_single($res,$pay_order['log_id']);
                        }
                    }

                    //$louxiaoer = new \SDXApi\Service\LouxiaoerService();
                    $distribution = new OrderDistributionTimeService();


    				if(count($order_list)>0){
    					foreach ($order_list as $order_data){
                            $louxiaoer_data = array();
                            $remark = array();

                            //添加到用户行为(已付款状态)
                            $param = array('isertList', '' , 'consume',$order_data['order_id'], $order_data['wid']);
                            \Think\Hook::listen('receng', $param);

                            //订单绑定楼小二
                            //$louxiaoer_data = $louxiaoer->order_binding_louxiaoer($order_data['order_id']);

    						//发送短信
    						if($order_data['shipping_id']==2 && $order_data['is_presell']==0 && $pay_order['referer']!='891'){
    							//自提订单短信
    						    $expected_pickup_time=D("Orderinfo")->get_expected_pickup_time($order_data);

                                $wechat_param=array();

                                switch($_SERVER['SERVER_NAME']){
                                    case 'api.xian3.com':
                                        $thisurl='xian3.com';
                                        break;
                                    case 'api.test.shidexian.com':
                                        $thisurl='test.shidexian.com';
                                        break;
                                    case 'api.shidexian.com':
                                        $thisurl='w.shidexian.com';
                                        break;
                                    default:
                                        $thisurl='w.shidexian.com';
                                        break;
                                }
                                $oid=$order_data['user_id'];
                                $Code=md5($oid.'sdx@9999');


                                $wechat_param['url']="https://".$thisurl."/?index=/ordInfo?ordId=".$order_data['order_id']."&utm_source=GZHorder_booking_self_new";
                                $wechat_param['first']='尊敬的'.$order_data['consignee'].'，逾期系统将自动为您取消自提订单，请尽快前往门店领取商品。';
                                $wechat_param['keyword1']=$order_data['order_sn'];
                                $wechat_param['keyword2']=$expected_pickup_time;
                                $wid_info=D("orderinfo")->get_wid_info($order_data['wid']);
                                $wechat_param['keyword3']=$wid_info['sender_address'].$wid_info['sender'];

                                $receipt_code = D("users")->get_order_receipt_code($order_data['order_id']);
                                $wechat_param['remark']='自提时请向收银员出示提货码'.$receipt_code;
    						    
    							$send_result = A("Smsapi")->send_message_api('order_pay_ok_self_new',$order_data['mobile'],$order_data['consignee'],'',$order_data['order_sn'],'',$order_data['user_id'],array('time'=>$expected_pickup_time,'receipt_code'=>$receipt_code),'',$wechat_param);
    						}else if($order_data['shipping_id']==2 && $order_data['is_presell']==1 && $pay_order['referer']!='891'){
    						   //自提预售订单短信
    						   $expected_pickup_time=D("Orderinfo")->get_expected_pickup_time($order_data);
    						   $wechat_param=array();
    						   	
    						   switch($_SERVER['SERVER_NAME']){
    						       case 'api.xian3.com':
    						           $thisurl='xian3.com';
    						           break;
    						       case 'api.test.shidexian.com':
    						           $thisurl='test.shidexian.com';
    						           break;
    						       case 'api.shidexian.com':
    						           $thisurl='w.shidexian.com';
    						           break;
    						       default:
    						           $thisurl='w.shidexian.com';
    						           break;
    						   }
    						   $oid=$order_data['user_id'];
    						   $Code=md5($oid.'sdx@9999');
    						   
    						   	
    						   $wechat_param['url']="https://".$thisurl."/?index=/ordInfo?ordId=".$order_data['order_id']."&utm_source=GZHorder_booking_self_new";
    						   $wechat_param['first']='尊敬的'.$order_data['consignee'].'，逾期系统将自动为您取消自提订单，请尽快前往门店领取商品。';
    						   $wechat_param['keyword1']=$order_data['order_sn'];
    						   $wechat_param['keyword2']=$expected_pickup_time;
                                $wid_info=D("orderinfo")->get_wid_info($order_data['wid']);
                                $wechat_param['keyword3']=$wid_info['sender_address'].$wid_info['sender'];

                                $receipt_code = D("users")->get_order_receipt_code($order_data['order_id']);
                                $wechat_param['remark']='自提时请向收银员出示提货码'.$receipt_code;
    						   
    						    $send_result = A("Smsapi")->send_message_api('order_booking_self_new',$order_data['mobile'],$order_data['consignee'],'',$order_data['order_sn'],'',$order_data['user_id'],array('time'=>$expected_pickup_time),'',$wechat_param);
    						}else if($pay_order['referer']!='891'){
                                date_default_timezone_set('PRC');
//    							//配送订单短信best_time_start
    							//if($order_data['best_time_start']>0){//兼容老版本
    								$remark['best_time'] = date("Y-m-d H:i",$order_data['best_time_start']) . '-' . date("H:i",$order_data['best_time']);
//    							}else{
////    								$remark['best_time'] = date("Y-m-d H:i",($order_data['best_time']-2*3600));
//                                    if (!empty($order_data['best_time'])) {
//                                        $remark['best_time'] = date("Y-m-d H:i",($order_data['best_time']-2*3600));
//                                    }
//                                    else{
//                                        $today = strtotime(date('Y-m-d 22:00'));
//                                        $time = time();
//                                        if ($time > $today) {
//                                            $base_time = date('Y-m-d 10:00', strtotime('+1 day'));
//                                        }
//                                        else{
//                                            $base_time = date('Y-m-d 10:00');
//                                        }
//                                        $remark['best_time'] = $base_time;
//                                    }
//    							}


                                
                                $order_goods_list=M("order_goods")->field("goods_name")->where(array('order_id'=>$order_data['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_data['order_id'].')')))->select();
                                $goods_name=array();
                                foreach($order_goods_list as $goods_list_item){
                                    $goods_name[]=$goods_list_item['goods_name'].' ';
                                }
                                
                                $wechat_param=array();
                                switch($_SERVER['SERVER_NAME']){
                                    case 'api.xian3.com':
                                        $thisurl='xian3.com';
                                        break;
                                    case 'api.test.shidexian.com':
                                        $thisurl='test.shidexian.com';
                                        break;
                                    case 'api.shidexian.com':
                                        $thisurl='w.shidexian.com';
                                        break;
                                    default:
                                        $thisurl='w.shidexian.com';
                                        break;
                                }
                                $oid=$order_data['user_id'];
                                $Code=md5($order_data['user_id'].'sdx@9999');
                                
                                $get_orderinfo=M("order_info")->where(array('order_id'=>$order_data['order_id']))->field("consignee,address,order_sn,order_amount,money_paid,surplus")->find();



                                $wechat_param['first']='尊敬的'.$get_orderinfo['consignee'].'，您所订购的商品已支付成功，预计配送时间为'.$remark['best_time'].'，请耐心等待配送。';
                                $wechat_param['orderProductPrice']=sprintf("%.2f",($get_orderinfo['order_amount']+$get_orderinfo['money_paid']+$get_orderinfo['surplus']));
                                $wechat_param['orderProductName']=implode(",",$goods_name);
                                $wechat_param['orderAddress']=$get_orderinfo['address'];
                                $wechat_param['orderName']=$get_orderinfo['order_sn'];

                                //检查订单是否超时免单
                                if($order_data['shipping_id']==3 && $order_data['196_admin_id']==0){
                                    if($distribution->check_order_free_single($order_data['order_id'])){
                                        $remark['additional'] = '您的订单若在预计配送时间段内未送达，我们将为您免单。';
                                    }
                                }

                                //如果绑定楼小二（发送楼小二模板消息）
                                if($louxiaoer_data['name'] && $louxiaoer_data['phone']){
                                    $wechat_param['remark']='收到货后如发现商品有异常，生鲜食品请在可在签收后24小时内拍照与提交售后工单，我们将为您进行处理。';
                                    $wechat_param['url']="https://".$thisurl."/?index=/ordInfo?ordId=".$order_data['order_id']."&utm_source=GZHorder_pay_ok_distribute_lou";
                                    $send_result = A("Smsapi")->send_message_api('order_pay_ok_distribute_lou',$order_data['mobile'],$order_data['consignee'],'',$order_data['order_sn'],'',$order_data['user_id'],$remark,'',$wechat_param,$louxiaoer_data);
                                    
                                }else{
                                    $wechat_param['remark']='收到货后如发现商品有异常，生鲜食品请在可在签收后24小时内拍照与提交售后工单，我们将为您进行处理。';
                                    $wechat_param['url']="https://".$thisurl."/?index=/ordInfo?ordId=".$order_data['order_id']."&utm_source=GZHorder_pay_ok_distribute";
                                    $send_result = A("Smsapi")->send_message_api('order_pay_ok_distribute',$order_data['mobile'],$order_data['consignee'],'',$order_data['order_sn'],'',$order_data['user_id'],$remark,'',$wechat_param);

                                }

    						}
    					}
    				}else{

                        //添加到用户行为(已付款状态)
                        $param = array('isertList', '' , 'consume',$pay_order['order_id'], $pay_order['wid']);
                        \Think\Hook::listen('receng', $param);

                        //订单绑定楼小二
                        //$louxiaoer_data = $louxiaoer->order_binding_louxiaoer($pay_order['order_id']);

    					//发送短信
    					if($pay_order['shipping_id']==2 && $pay_order['referer']!='891'){
    						//自提订单短信
    					    $expected_pickup_time=D("Orderinfo")->get_expected_pickup_time($pay_order);

                            $wechat_param=array();

                            switch($_SERVER['SERVER_NAME']){
                                case 'api.xian3.com':
                                    $thisurl='xian3.com';
                                    break;
                                case 'api.test.shidexian.com':
                                    $thisurl='test.shidexian.com';
                                    break;
                                case 'api.shidexian.com':
                                    $thisurl='w.shidexian.com';
                                    break;
                                default:
                                    $thisurl='w.shidexian.com';
                                    break;
                            }
                            $oid=$order_data['user_id'];
                            $Code=md5($oid.'sdx@9999');


                            $wechat_param['url']="https://".$thisurl."/?index=/ordInfo?ordId=".$order_data['order_id']."&utm_source=GZHorder_booking_self_new";
                            $wechat_param['first']='尊敬的'.$pay_order['consignee'].'，逾期系统将自动为您取消自提订单，请尽快前往门店领取商品。';
                            $wechat_param['keyword1']=$pay_order['order_sn'];
                            $wechat_param['keyword2']=$expected_pickup_time;
                            $wid_info=D("orderinfo")->get_wid_info($order_data['wid']);
                            $wechat_param['keyword3']=$wid_info['sender_address'].$wid_info['sender'];

                            $receipt_code = D("users")->get_order_receipt_code($pay_order['order_id']);
                            $wechat_param['remark']='自提时请向收银员出示提货码'.$receipt_code;

    						$send_result = A("Smsapi")->send_message_api('order_pay_ok_self_new',$pay_order['mobile'],$pay_order['consignee'],'',$pay_order['order_sn'],'',$pay_order['user_id'],array('time'=>$expected_pickup_time,'receipt_code'=>$receipt_code),'',$wechat_param);
    					}else if($pay_order['referer']!='891'){
    						//配送订单短信
    						if($pay_order['best_time_start']>0){
    							$remark['best_time'] = date("Y-m-d H:i",$pay_order['best_time_start']) . '-' . date("H:i",$pay_order['best_time']);
    						}else{
    							$remark['best_time'] = date("Y-m-d H:i",($pay_order['best_time']-2*3600));
    						}


                            
                            $order_goods_list=M("order_goods")->field("goods_name")->where(array('order_id'=>$pay_order['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$pay_order['order_id'].')')))->select();
                            
                            $goods_name=array();
                            foreach($order_goods_list as $goods_list_item){
                                $goods_name[]=$goods_list_item['goods_name'].' ';
                            }
                            
                            $wechat_param=array();
                            switch($_SERVER['SERVER_NAME']){
                                case 'api.xian3.com':
                                    $thisurl='xian3.com';
                                    break;
                                case 'api.test.shidexian.com':
                                    $thisurl='test.shidexian.com';
                                    break;
                                case 'api.shidexian.com':
                                    $thisurl='w.shidexian.com';
                                    break;
                                default:
                                    $thisurl='w.shidexian.com';
                                    break;
                            }
                            $oid=$pay_order['user_id'];
                            $Code=md5($pay_order['user_id'].'sdx@9999');

                            $get_orderinfo=M("order_info")->where(array('order_id'=>$pay_order['order_id']))->field("consignee,address,order_sn,order_amount,money_paid,surplus")->find();
                                	
                                
                                $wechat_param['first']='尊敬的'.$pay_order['consignee'].'，您所订购的商品已支付成功，预计配送时间为'.$remark['best_time'].'，请耐心等待配送。';
                                $wechat_param['orderProductPrice']=sprintf("%.2f",($get_orderinfo['order_amount']+$get_orderinfo['money_paid']+$get_orderinfo['surplus']));
                                $wechat_param['orderProductName']=implode(",",$goods_name);
                                $wechat_param['orderAddress']=$get_orderinfo['address'];
                                $wechat_param['orderName']=$get_orderinfo['order_sn'];

                            //检查订单是否超时免单
                            if($pay_order['shipping_id']==3 && $pay_order['196_admin_id']==0){
                                if($distribution->check_order_free_single($pay_order['order_id'])){
                                    $remark['additional'] = '您的订单若在预计配送时间段内未送达，我们将为您免单。';
                                }
                            }

                            //如果绑定楼小二（发送楼小二模板消息）
                            if($louxiaoer_data['name'] && $louxiaoer_data['phone']){

                                $wechat_param['remark']='收到货后如发现商品有异常，生鲜食品请在可在签收后24小时内拍照与提交售后工单，我们将为您进行处理。';
                                $wechat_param['url']="https://".$thisurl."/?index=/ordInfo?ordId=".$pay_order['order_id']."&utm_source=GZHorder_pay_ok_distribute_lou";
                                $send_result = A("Smsapi")->send_message_api('order_pay_ok_distribute_lou',$pay_order['mobile'],$pay_order['consignee'],'',$pay_order['order_sn'],'',$pay_order['user_id'],$remark,'',$wechat_param,$louxiaoer_data);

                            }else{
                                $wechat_param['remark']='收到货后如发现商品有异常，生鲜食品请在可在签收后24小时内拍照与提交售后工单，我们将为您进行处理。';

                                $wechat_param['url']="https://".$thisurl."/?index=/ordInfo?ordId=".$pay_order['order_id']."&utm_source=GZHorder_pay_ok_distribute";
                                $send_result = A("Smsapi")->send_message_api('order_pay_ok_distribute',$pay_order['mobile'],$pay_order['consignee'],'',$pay_order['order_sn'],'',$pay_order['user_id'],$remark,'',$wechat_param);

                            }


    					}
    				}

    			}



    		}elseif ($pay_order['order_type'] == PAY_SURPLUS){
                $user_account = D('user_account');
                $res_id = $user_account->where(array('id'=>$pay_order['order_id'],'is_paid'=>1))->getField('id');
                if (empty($res_id)) {
                    /* 更新会员预付款的到款状态 */
                    $setdata = array('paid_time'=>gmtime(),'is_paid'=>1);
                    $map = array('id'=>$pay_order['order_id']);
                    $user_account->where($map)->setField($setdata);

                    /* 取得添加预付款的用户以及金额 */
                    $account_info = $user_account->where($map)->find();
                    /* 修改会员帐户金额 */
                    $this->log_account_change($account_info['user_id'], $account_info['amount'], 0, 0, 0, "充值", ACT_SAVING);
                }
            }else{
    			/* 取得已发货的虚拟商品信息 */
    			$post_virtual_goods = $order_info->get_virtual_goods($pay_order['order_id'], true);
    			/* 有已发货的虚拟商品 */
    			if(!empty($post_virtual_goods)){
    				$msg = '';
    				/* 检查两次刷新时间有无超过12小时 */
    				$where = array('order_id'=>$pay_order['order_id']);
    				$row = $order_info->field('pay_time, order_sn')->where($where)->find();
    				$intval_time = gmtime() - $row['pay_time'];
    				if ($intval_time >= 0 && $intval_time < 3600 * 12) {
    					$virtual_card = array();
    					foreach ($post_virtual_goods as $code => $goods_list) {
    						/* 只处理虚拟卡 */
    						if ($code == 'virtual_card') {
    							foreach ($goods_list as $goods) {
    								$info = $order_info->virtual_card_result($row['order_sn'], $goods);
    								if (!empty($info)) {
    									$virtual_card[] = array('goods_id' => $goods['goods_id'], 'goods_name' => $goods['goods_name'], 'info' => $info);
    								}
    							}
    							$result['virtual_card'] = $virtual_card;
    						}
    					}
    				} else {
    					$msg = '商品已发货，详情请到用户中心订单详情查看';
    					
    				}
    				$pay_success = "您此次的支付操作已成功！" . $msg;
    				$result['pay_success'] = $pay_success;
    			}
    			
    			/* 取得未发货虚拟商品 */
    			$virtual_goods = $order_info->get_virtual_goods($pay_order['order_id'], false);
    			if (!empty($virtual_goods)) {
    				$pay_success = '您此次的支付操作已成功！自动发货失败，请尽快联系商家重新发货';
    				$result['pay_success'] = $pay_success;
    			}
    		}
    		if(!$result['pay_success']){
    			$msg = '详情请到用户中心订单详情查看。';
    			$pay_success = "您此次的支付操作已成功！" . $msg;
    			$result['pay_success'] = $pay_success;
    		}
    	}

    	return $result;
    }
    /**
     * 根据out_trade_no订单号获取log_id;
     */
    public function get_pay_log($out_trade_no = '',$order_type=PAY_ORDER,$state=false) {
    	$pay_log = M('pay_log');
    	if($order_type==PAY_ORDER||$state===true){
    	   
    		//$pay_log_data = $pay_log->alias('p')->join("sdx_order_info o on o.order_id = p.order_id")->where(array('o.order_sn'=>'"'.$out_trade_no.'"','p.order_type'=>$order_type))->find();
            $pay_log_data = $pay_log->alias('p')->join("sdx_order_info o on o.order_id = p.order_id")->where("o.order_sn='$out_trade_no' and p.order_type=$order_type")->find();
    	}else{
    		$pay_log_data = $pay_log->alias('p')->join("sdx_user_account uc on uc.id = p.order_id")->where(array("p.log_id"=>$out_trade_no,'p.order_type'=>$order_type))->find();
    	}
    	
		return $pay_log_data;
    }
    
    
    /**
     * 保存支付宝交易号trade_no
     * @param array $trade_data
     * @param string $order_type
     */
    public function update_alipay_log($trade_data,$order_type=PAY_ORDER){
    	$pay_order = $this->get_pay_log($trade_data['out_trade_no'],$order_type);
    	$data = array();
    	$data['transid'] = $trade_data['trade_no'];
    	D('pay_log')->where(array('log_id'=>$pay_order['log_id']))->save($data);
    }

    /**
     * 保存京东支付交易号
     * @param $trade_data
     * @param int $order_type
     */
    public function update_jdpay_log($trade_data,$order_type=PAY_ORDER){
        $pay_order = $this->get_pay_log($trade_data['out_trade_no'],$order_type);
        $data = array();
        $data['transid'] = $trade_data['tradeNum'];

        D('pay_log')->where(array('log_id'=>$pay_order['log_id']))->save($data);
    }
    
    /**
     * 获取支付方式pay_code
     * @param int $pay_id
     * @return string pay_cod 
     */
    public function get_pay_code($pay_id){
    	return $this->where(array('pay_id'=>$pay_id))->getField('pay_code');
    }
    
    public function write_log($message,$filename){
    	$log = new Log();
    	$destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';
    
    	$log->write($message,'DEBUG','',$destination);
    }
    
    /*
     * 余额支付外部调用接口
     */
    public function tobalance_pay($order_sn='') {
        
        $order_info = M('order_info');
        $map = array('order_sn'=>$order_sn);
        $order = $order_info->where($map)->find();
        $res=$this->balance_pay($order, "",false);
        if($res){
            return true;
        }else{
            return false;
        }
   
    }
    
    
    /**
     * 余额支付
     * @param $order
     * @param $pwd
     */
    private function balance_pay($order, $pwd, $needpwd=true) {
         
         
        if(empty($pwd)&&$needpwd===true){
            returnApiError('请输入密码');
        }
    
        if(!$this->check_pay_password($order['user_id'], $pwd)&&$needpwd===true){
            returnApiError('支付密码错误');
        }
    
        $userinfo = D('users')->where(array('user_id'=>$order['user_id']))->find();
    
        //        检查余额
        if($order ['order_amount'] > ($userinfo ['user_money'] + $userinfo ['credit_line'])){
            $res['error_code'] = "103";
            $order_data = $this->pay_order_info($order);
            $order_data = array_merge($res,$order_data);
            returnApiError('账户余额不足',$order_data);
        }
    
        
    
        /* 插入支付日志 */
        $pay_log_id = $this->get_paylog_id($order['order_id'],PAY_ORDER);
        if(empty($pay_log_id)){
            $pay_log_id = $this->insert_pay_log($order['order_id'], $order ['order_amount'], PAY_ORDER);
        }
    
        //修改订单支付类型
        $this->change_order_pay_type($order, 3);
    
    
        //处理支付后的订单数据
        $result = $this->order_paid($order['order_sn']);
    
        if($result['pay_success']){
            if($needpwd===true){
                $field = 'order_sn,pay_name,surplus+money_paid as pay_amount,shipping_name,shipping_id';
                $order_data = M('order_info')->field($field)->where(array('order_id'=>$order['order_id']))->find();
                $order_data = array_merge($result,$order_data);
    
                /**
                 * 到店自提单
                */
                if($order_data['shipping_id'] == 2){
                    $this->add_alarmLog_type($order_data['order_sn'], 4);
                }
    
                returnApiSuccess($order_data,'支付成功');
            }else{
                return true;
            }
        }else{
            if($needpwd===true){
                $field = 'order_sn,pay_name,order_amount as pay_amount,shipping_name';
                $order_data = M('order_info')->field($field)->where(array('order_id'=>$order['order_id']))->find();
                returnApiError('支付不成功，请重试',$order_data);
            }else{
                return false;
            }
        }
    }
    
    /**
     * 检查用户支付密码
     * @param $userid 用户id
     * @param $password 用户密码
     * @return bool
     */
    private function check_pay_password($userid, $password)
    {
        $userinfo = D('users')->where(array('user_id'=>$userid))->find();
    
        if($userinfo['paypwd'] == $password){
    
            return true;
    
        }
    
        return false;
    }
    
    private function pay_order_info($order){
        $data = array();
        $data['order_sn'] = $order['order_sn'];
        $data['pay_name'] = $order['pay_name'];
        $data['pay_amount'] = $order['surplus']+$order['money_paid']+$order['order_amount'];
        $data['shipping_name'] = $order['shipping_name'];
        $data['order_sn'] = $order['order_sn'];
        return $data;
    }
    

    private function change_order_pay_type($order,$pay_id){
        if($pay_id != $order['pay_id']){
            $payment = D('Cart')->payment_info($pay_id);
            $data['pay_name'] = addslashes($payment ['pay_name']);
            $data['pay_id'] = $pay_id;
            	
            D('order_info')->where(array('order_id'=>$order['order_id']))->save($data);
            return true;
        }
        return false;
    }
    
    /**
     * 插入预警日志
     * Created by Jerry
     * @param $order_sn
     * @param null $type
     * @return bool
     */
    protected function add_alarmLog_type($order_sn='', $type = null)
    {
        $alarmModel = D('AlarmLog');
        $data = array(
            'type'          =>  $type,
            'order_sn'      =>  $order_sn,
            'trigger_time'  =>  time(),
        );
        $rs = $alarmModel->add($data);
    
        if(!$rs){
            return false;
        }
    
        return true;
    }
    
}